import RNFetchBlob from 'rn-fetch-blob';
const {fs, config} = RNFetchBlob;

function getTemporaryPathForDownload(dest) {
  return dest + '.download';
}

/**
 *
 * @param {*} dest 保存目录
 * @param {*} url 下载链接
 * @returns
 */
function resumableDownload(dest, url, taskCall, progress) {
  //解析文件名称
  let paths = url.split('/');
  let sourceName = paths[paths.length - 1];
  dest = dest + '/' + sourceName;

  console.log('下载文件路径为' + dest);

  return new Promise((resolve, reject) => {
    let tmpPath = getTemporaryPathForDownload(dest);
    fs.exists(tmpPath)
      .then((ext) => {
        // if the tmp file exists, which means the previous
        // download session was interrupted.
        // append data in content ${dest}.download to destination
        if (ext) {
          // specify encoding `uri` is the most performant way
          // to perform file-to-file data transfer,
          // the whole process is done in native
          //   return fs.stat(tmpPath);
          return fs.appendFile(dest, tmpPath, 'uri').then(async () => {
            await fs.unlink(tmpPath);
            return fs.stat(dest);
          });
        } else {
          return fs.exists(dest).then((exist) => {
            if (exist) {
              return fs.stat(dest);
            } else {
              return Promise.resolve({size: 0});
            }
          });
        }
      })
      // after the previous downloaded data moved to desitation (if there is)
      // we can start a new session which overwrites the ${dest}.download
      // the new seesion will use range request which ask for the remain
      // part from server
      .then((stat) => {
        console.log('统计到资源大小为', stat.size);

        let task = RNFetchBlob.config({path: tmpPath});
        taskCall && taskCall(task);
        return task
          .fetch('GET', url, {
            Range: `bytes=${stat.size}-`,
          })
          .progress((received, total) => {
            progress &&
              progress(
                Number(stat.size) + Number(received),
                Number(stat.size) + Number(total),
              );
          });
      })
      // if the task completed, write the content to the true destination
      .then((res) => fs.appendFile(dest, res.path(), 'uri'))
      // remove tmp file ( file at ${dest}.download )
      .then(() => {
        return fs.unlink(tmpPath);
      })
      .then(() => {
        /* done !! */
        console.log('下载成功');
        resolve(dest);
      })
      .catch((err) => {
        console.log('下载文件错误' + err);
        reject(err);
      });
  });
}

module.exports = {
  resumableDownload,
};
